
import jsonp from 'jsonp';

export default class Api {

  static searchUrl = "http://songsearch.kugou.com/song_search_v2";//歌曲搜索链接
  static detailUrl = "http://wwwapi.kugou.com/yy/index.php";//歌曲详情链接
  static get(url, params) {
    return new Promise((resolve, reject) => {
      jsonp(url + "?" + this.toQueryString(params), null, (err, data) => {
        if (!err) {
          if (data.status === 1) {
            resolve(data.data)
          } else {
            reject(data)
          }
        } else {
          reject(err)
        }
      })
    })
  }

  // JSON参数序列化
  static toQueryString(obj) {
    let result = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor === Array) {
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        result = result.concat(queryValues);
      } else {
        result.push(this.toQueryPair(key, values));
      }
    }
    return result.join('&');
  }
  static toQueryPair(key, value) {
    if (typeof value === 'undefined') {
      return key;
    }
    return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  }
}